package com.ruoyi.web.controller.client;/**
 * Created by XiaoYi  on 2020-03-30 15:02
 */

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.GetUserId;
import com.ruoyi.common.enums.OperatorType;
import com.ruoyi.common.enums.RequestType;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.yf.domain.YfDept;
import com.ruoyi.yf.domain.YfHospitalIndividuationData;
import com.ruoyi.yf.domain.YfTag;
import com.ruoyi.yf.domain.interfaces.YfType;
import com.ruoyi.yf.domain.mobile.YfMobileDeptNurse;
import com.ruoyi.yf.service.IYfDeptService;
import com.ruoyi.yf.service.IYfHospitalIndividuationDataService;
import com.ruoyi.yf.tool.barcode.Rules;
import io.swagger.annotations.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * XiaoYi...
 * <p>
 * 客户端数据接口
 */
@RequestMapping("/client/data")
@RestController
@Api(tags = "基本接口")
public class ClientInterfaceController extends BaseController {

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IYfDeptService yfDeptService;

    @Autowired
    private IYfHospitalIndividuationDataService hospitalIndividuationDataService;

    /**
     *  获取医废类型
     *  c289cf22-cd32-4c00-acbe-c4e5595d43a2
     */
    @ApiOperation(value = "获取医废类型", notes = "获取医废类型", produces = "application/json")
    @RequestMapping(method = RequestMethod.POST, value = "/type")
    public TableDataInfo<SysDictData> getYFType() {
        List<SysDictData> dictData = dictDataService.yfType();
        return getDataTable(dictData);

    }


    /**
     *  获取用户所在医院的科室
     *  59f04e87-65fc-4282-98f0-6dc71cedafac
     */
    @ApiOperation(value = "获取科室", notes = "获取科室")
    @RequestMapping(method = RequestMethod.POST, value = "/dept")
    @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Long")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没填好"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    /**
     * adb57b7e-2273-47a4-ac37-64ddcbfa53b4
     */
    public TableDataInfo<YfDept> getdepartment(Long uid) {
        if (uid == null) {
            TableDataInfo dataTable = new TableDataInfo();
            dataTable.setMsg("请检查参数");
            dataTable.setCode(1001);
            return dataTable;
        }

        List<YfDept> dept = yfDeptService.getUserIdDepartment(uid);
        return getDataTable(dept);
    }



    /**
     *  获取用户所在医院的科室 , 获取医废类型
     *  047bb467-be46-4aca-bc60-86992df076ba
     */
    @ApiOperation(value = "获取科室和医废类型", notes = "获取科室和医废类型")
    @RequestMapping(method = RequestMethod.POST, value = "/getKSListAndYFTypeList")
    @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Long")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没填好"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    /**
     *        71784574-41a2-4c1f-aee8-dbea1c567e83
     */
    public HashMap<String,Object> getKSListAndYFTypeList(Long uid) {
        HashMap<String,Object> hashMap = new HashMap<>();
        if (uid == null) {
            TableDataInfo dataTable = new TableDataInfo();
            dataTable.setMsg("请检查参数");
            dataTable.setCode(1001);
            hashMap.put("dataTable",dataTable);
            return hashMap;
        }
        // 获取科室
        List<YfDept> deptlist = yfDeptService.getUserIdDepartment(uid);
        // 获取所有医废类型  yfType()
        List<SysDictData> dictDatalist = dictDataService.getAllYfType();


        hashMap.put("kSList",getDataTable(deptlist));
        hashMap.put("yFTypeList",getDataTable( yfTypeChange(dictDatalist, uid)) );

        return hashMap;
    }


    private List<YfType> yfTypeChange(List<SysDictData> dictDatalist, Long uid){
        // 按采集员id获取医院胎盘和危废的配置 -- 默认胎盘显示，所有危废不显示
        List<YfHospitalIndividuationData> pzlist = hospitalIndividuationDataService.selectYfHospitalTPAndWFConfigListByUid(uid);
        if( pzlist == null || pzlist.isEmpty() ){
            // 未查询到医院关于胎盘、危废的配置，过滤掉危废 -- dictValue 11及之后
            dictDatalist = dictDatalist.stream()
                    .filter( dict -> (Integer.parseInt(dict.getDictValue()) <= 20 ) )
                    .collect(Collectors.toList());
        }else{  // 有查询到胎盘或危废
            int num = 0;
            for (int i = 0; i < pzlist.size(); i++) {
                // 胎盘 -- 不是true（包括空）时隐藏
                if( pzlist.get(i).getDictType().equals("placenta_statistics")
                        && !"true".equals(pzlist.get(i).getDictValue()) ){
                    dictDatalist = dictDatalist.stream()
                            .filter( dict -> Integer.parseInt(dict.getDictValue()) != 6  )
                            .collect(Collectors.toList());
                }else if( pzlist.get(i).getDictType().equals("wf_statistics") ){  // 危废 -- 不是true（包括空）时隐藏
                    num ++;
                    if( !"true".equals(pzlist.get(i).getDictValue()) ){
                        dictDatalist = dictDatalist.stream()
                                .filter( dict -> (Integer.parseInt(dict.getDictValue()) <= 20 ) )
                                .collect(Collectors.toList());
                    }
                }
            }
            // 如果配置里没有关于危废的则隐藏
            if( num == 0 ){
                dictDatalist = dictDatalist.stream()
                        .filter( dict -> (Integer.parseInt(dict.getDictValue()) <= 20 ) )
                        .collect(Collectors.toList());
            }
        }

        List<YfType> yftypelist = new ArrayList<>();
        for (int i = 0; i < dictDatalist.size(); i++) {
            yftypelist.add(new YfType(dictDatalist.get(i).getDictCode(),
                    dictDatalist.get(i).getDictLabel(),dictDatalist.get(i).getDictValue()));
        }

        return yftypelist;
    }


    /**
     *  获取用户所在医院的科室的护士列表 , 获取医废类型
     *  a0c1a9ca-9681-4926-8fe0-ad4f08e561d1
     */
    @ApiOperation(value = "获取科室护士和医废类型", notes = "获取科室护士和医废类型")
    @RequestMapping(method = RequestMethod.POST, value = "/getKSNuserListAndYFTypeList")
    @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Long")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没填好"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    public HashMap<String,Object> getKSNuserListAndYFTypeList(Long uid) {
        HashMap<String,Object> hashMap = new HashMap<>();
        if (uid == null) {
            TableDataInfo dataTable = new TableDataInfo();
            dataTable.setMsg("请检查用户id参数");
            dataTable.setCode(1001);
            hashMap.put("dataTable",dataTable);
            return hashMap;
        }
        // 根据用户获取所在医院的科室护士列表
        List<YfMobileDeptNurse> deptlist = yfDeptService.getKSNuserListByUid(uid);
        // 获取医废类型
        // List<SysDictData> dictDatalist = dictDataService.yfType();
        List<SysDictData> dictDatalist = dictDataService.getAllYfType();
        hashMap.put("kSList",getDataTable(deptlist));
        hashMap.put("yFTypeList",getDataTable( yfTypeChange(dictDatalist, uid) ) );

        return hashMap;
    }


    /**
     * 验证条形码规则正确否  -- 22位
     * @param pcode
     * @return
     * 915f02a8-c596-4879-9f4f-6c1fba2cbd0a
     */
    @PostMapping("/barcode/validation")
    @ResponseBody
    public AjaxResult validationBarcode(@Param("pcode") String pcode) {
        // System.out.println("code:" + pcode);
        boolean b = Rules.codeCheckLong(pcode);
        if (b)
            return AjaxResult.success("条码验证成功", b);
        return AjaxResult.error("条码验证失败", b);
    }


//    // 接口-局端接收院端数据接口
//    59bfd7f9-1f99-45fb-8c4b-cbe2c9334683
//    @ApiOperation(value = "接口-局端接收院端数据接口")
////    @ApiImplicitParam(name = "yfTag", value = "医废", dataType = "YfTag", allowMultiple = true)
//    @RequestMapping(method = RequestMethod.POST, value = "/hospitalYFDataUpload")
////    @Log(title = "接口-局端接收院端数据接口", businessType = BusinessType.INSERT, operatorType = OperatorType.MOBILE,
////            requestType = RequestType.JSON, getUserId = GetUserId.JSONMOREYFTAG)
//    public AjaxResult newupload(@RequestBody List<YfTag> tags) {
//        Date date = new Date();
//        for (int i = 0; i < tags.size(); i++) {
//            tags.get(i).setCodeid(new Rules().longBarcode());       // 条码
//            logger.debug("   ------------  " + tags.get(i).getCodeid());
//            tags.get(i).setIntoDate(date);
//            tags.get(i).setTrashStatus("20");
//            tags.get(i).setCollectUpdateDate(date);
//            tags.get(i).setCreateTime(date);
//            tags.get(i).setUpdateWay("0");
//        }
//        int i = yfTagService.insertYfTagList(tags);
//        if (i < 0){
//            return AjaxResult.error("入库失败！");
//        }
//        return AjaxResult.success("入库成功！");
//    }



}
